﻿using System;
using System.Net;
using Org.Flowertwig.Media.Information.Services;

namespace Org.Flowertwig.Media
{
    public class Web
    {
        //public static string GetPage(string url, string method, string contentType)
        //{
        public static string GetPage(string url)
        {
            var id = Hash.CreateId(url);
            var cache = Storage.GetCache(id);

            if (cache != null)
                return cache.Data;

            string tmp = string.Empty;
            try
            {
                WebClient webClient = new WebClient();
                tmp = webClient.DownloadString(url);

                //HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(url);
                //wReq.UserAgent = "FlowMedia";

                //// Get the response stream.
                //WebResponse wResp = wReq.GetResponse();
                //Stream respStream = wResp.GetResponseStream();
                //StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                //tmp = reader.ReadToEnd();

                //// Close the response and response stream.
                //wResp.Close();
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }

            if (!string.IsNullOrEmpty(tmp))
            {
                Storage.AddCache(new Cache
                                     {
                                         Id = id,
                                         Data = tmp,
                                         Added = DateTime.Now
                                     });

                // We should be nice to TVRage and wait 4 sec after each request.
                //System.Threading.Thread.Sleep(4000);

            }
            return tmp;
        }
    }
}
